package com.example.jpetstoreclient.controller;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

//解决跨域问题
@Configuration
@WebFilter(filterName = "CORSFilter")
public class CORSFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));//谁请求就允许谁跨域
        response.setHeader("Access-Control-Allow-Credentials","true");//允许携带cookie
        response.setHeader("Access-Control-Allow-Methods","POST,GET,PATCH,DELETE,PUT");//允许的请求方式
        response.setHeader("Access-Control-Max-Age","3600");//最长缓存时间
        response.setHeader("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");

        filterChain.doFilter(request,response);//继续过滤器链
    }
}
